#!/bin/bash
set -e

# 备份库
DB_USER="root"
DB_PASS=""
DB_HOST=""
DB_PORT=""
DB_THREADS="4"
DB_NAME=""
TABLES=("user" "product")

# 还原库
TO_DB_USER="root"
TO_DB_PASS=""
TO_DB_HOST=""
TO_DB_PORT=""
TO_DB_THREADS="4"
TO_DB_NAME=""

# 备份目录
BACKUP_DIR="/backup/tablefile"

# 获取当前日期
CURRENT_DATE=$(date +%Y%m%d)
CURRENT_MONTH=$(date +%Y%m)

# 创建备份目录
BACKUP_PATH="$BACKUP_DIR/$CURRENT_MONTH/$CURRENT_DATE"
mkdir -p $BACKUP_PATH

# 构建表名列表
TABLE_LIST=""
for TABLE in "${TABLES[@]}"; do
    TABLE_LIST+="$DB_NAME.$TABLE,"
done
TABLE_LIST=${TABLE_LIST%,}
echo "备份表：$TABLE_LIST" 
# 备份表
mydumper -u $DB_USER -p $DB_PASS -h $DB_HOST -P $DB_PORT -t $DB_THREADS -T $TABLE_LIST -o $BACKUP_PATH --less-locking --clear


# 创建数据库
BACKUP_DB="$TO_DB_NAME"_"$CURRENT_MONTH"
mysql -u $TO_DB_USER -p$TO_DB_PASS -h $TO_DB_HOST -P $TO_DB_PORT -e "CREATE DATABASE IF NOT EXISTS $BACKUP_DB;"
sleep 1

# 还原备份
myloader -u $TO_DB_USER -p $TO_DB_PASS -h $TO_DB_HOST -P $TO_DB_PORT -B $BACKUP_DB -t $TO_DB_THREADS -e -d $BACKUP_PATH

sleep 1

# 修改表名
for TABLE in "${TABLES[@]}"; do
    NEW_TABLE_NAME="${TABLE}_$CURRENT_DATE"
    mysql -u $TO_DB_USER -p$TO_DB_PASS -h $TO_DB_HOST -P $TO_DB_PORT -e "RENAME TABLE $BACKUP_DB.$TABLE TO $BACKUP_DB.$NEW_TABLE_NAME;"
done

sleep 1

# 压缩备份文件
tar -czvf "$BACKUP_PATH.tar.gz" -C $BACKUP_DIR/$CURRENT_MONTH $CURRENT_DATE

# 清理临时文件
rm -rf $BACKUP_PATH

echo "备份和还原操作完成"
